<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="竞赛" prop="competitionId">
        <el-select v-model="queryParams.competitionId" placeholder="请选择竞赛" clearable style="width: 200px">
          <el-option
            v-for="competition in competitionList"
            :key="competition.id"
            :label="competition.name"
            :value="competition.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申诉标题" prop="appealTitle">
        <el-input
          v-model="queryParams.appealTitle"
          placeholder="请输入申诉标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable style="width: 150px">
          <el-option label="待审核" value="0" />
          <el-option label="已通过" value="1" />
          <el-option label="已拒绝" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="default" @click="handleQuery">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button size="default" @click="resetQuery">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="default"
          @click="handleAdd"
          v-hasPermi="['race:competitionAppeal:add']"
        >
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="default"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['race:competitionAppeal:edit']"
        >
          <el-icon><Edit /></el-icon>
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          size="default"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['race:competitionAppeal:remove']"
        >
          <el-icon><Delete /></el-icon>
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          size="default"
          @click="handleExport"
          v-hasPermi="['race:competitionAppeal:export']"
        >
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="appealList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申诉ID" align="center" prop="id" />
      <el-table-column label="竞赛名称" align="center" prop="competitionName" />
      <el-table-column label="参赛者" align="center" prop="participantName" />
      <el-table-column label="申诉标题" align="center" prop="appealTitle" :show-overflow-tooltip="true" />
      <el-table-column label="申诉理由" align="center" prop="appealReason" :show-overflow-tooltip="true" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" />
      <el-table-column label="联系邮箱" align="center" prop="contactEmail" />
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template #default="scope">
          <el-tag v-if="scope.row.auditStatus == 0" type="warning">待审核</el-tag>
          <el-tag v-else-if="scope.row.auditStatus == 1" type="success">已通过</el-tag>
          <el-tag v-else-if="scope.row.auditStatus == 2" type="danger">已拒绝</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核员" align="center" prop="auditorName" />
      <el-table-column label="审核时间" align="center" prop="auditTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="default"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['race:competitionAppeal:edit']"
          >
            <el-icon><Edit /></el-icon>
            修改
          </el-button>
          <el-button
            size="default"
            type="text"
            @click="handleAudit(scope.row)"
            v-hasPermi="['race:competitionAppeal:audit']"
            v-if="scope.row.auditStatus == 0"
          >
            <el-icon><Check /></el-icon>
            审核
          </el-button>
          <el-button
            size="default"
            type="text"
            @click="handleDetails(scope.row)"
          >
            <el-icon><View /></el-icon>
            详情
          </el-button>
          <el-button
            size="default"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['race:competitionAppeal:remove']"
          >
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改竞赛申诉管理对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="竞赛" prop="competitionId">
          <el-select v-model="form.competitionId" placeholder="请选择竞赛" @change="handleCompetitionChange" style="width: 100%">
            <el-option
              v-for="competition in competitionList"
              :key="competition.id"
              :label="competition.name"
              :value="competition.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="报名记录" prop="signupId">
          <el-select v-model="form.signupId" placeholder="请选择报名记录" @change="handleSignupChange" style="width: 100%">
            <el-option
              v-for="signup in signupList"
              :key="signup.id"
              :label="`${signup.participantName} - ${signup.contactPhone}`"
              :value="signup.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="申诉标题" prop="appealTitle">
          <el-input v-model="form.appealTitle" placeholder="请输入申诉标题（1-30字）" maxlength="30" show-word-limit />
        </el-form-item>
        <el-form-item label="申诉理由" prop="appealReason">
          <el-input v-model="form.appealReason" type="textarea" placeholder="请输入申诉理由（最多500字）" maxlength="500" show-word-limit :rows="4" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="联系邮箱" prop="contactEmail">
          <el-input v-model="form.contactEmail" placeholder="请输入联系邮箱" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审核申诉对话框 -->
    <el-dialog title="审核申诉" v-model="auditOpen" width="500px" append-to-body>
      <el-form ref="auditForm" :model="auditForm" :rules="auditRules" label-width="100px">
        <el-form-item label="申诉标题">
          <el-input v-model="auditForm.appealTitle" disabled />
        </el-form-item>
        <el-form-item label="申诉理由">
          <el-input v-model="auditForm.appealReason" type="textarea" disabled :rows="3" />
        </el-form-item>
        <el-form-item label="审核状态" prop="auditStatus">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核建议" prop="auditSuggestion">
          <el-input v-model="auditForm.auditSuggestion" type="textarea" placeholder="请输入审核建议" :rows="3" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAudit">确 定</el-button>
        <el-button @click="cancelAudit">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 申诉详情对话框 -->
    <el-dialog title="申诉详情" v-model="detailOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="申诉ID">{{ detailForm.id }}</el-descriptions-item>
        <el-descriptions-item label="竞赛名称">{{ detailForm.competitionName }}</el-descriptions-item>
        <el-descriptions-item label="参赛者">{{ detailForm.participantName }}</el-descriptions-item>
        <el-descriptions-item label="申诉标题">{{ detailForm.appealTitle }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ detailForm.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="联系邮箱">{{ detailForm.contactEmail }}</el-descriptions-item>
        <el-descriptions-item label="申诉理由" :span="2">
          <div style="white-space: pre-wrap;">{{ detailForm.appealReason }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag v-if="detailForm.auditStatus == 0" type="warning">待审核</el-tag>
          <el-tag v-else-if="detailForm.auditStatus == 1" type="success">已通过</el-tag>
          <el-tag v-else-if="detailForm.auditStatus == 2" type="danger">已拒绝</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审核员">{{ detailForm.auditorName }}</el-descriptions-item>
        <el-descriptions-item label="审核时间">{{ parseTime(detailForm.auditTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(detailForm.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="审核建议" :span="2" v-if="detailForm.auditSuggestion">
          <div style="white-space: pre-wrap;">{{ detailForm.auditSuggestion }}</div>
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDetail">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAppeal, getAppeal, delAppeal, addAppeal, updateAppeal, auditAppeal } from "@/api/race/appeal";
import { listCompetition } from "@/api/race/competition";
import { listCompetitionSignup } from "@/api/race/competitionSignup";
import { Search, Refresh, Plus, Edit, Delete, Download, Check, View } from '@element-plus/icons-vue';

export default {
  name: "Appeal",
  components: {
    Search,
    Refresh,
    Plus,
    Edit,
    Delete,
    Download,
    Check,
    View
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 竞赛申诉管理表格数据
      appealList: [],
      // 竞赛列表
      competitionList: [],
      // 报名记录列表
      signupList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示审核弹出层
      auditOpen: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        competitionId: null,
        appealTitle: null,
        auditStatus: null
      },
      // 表单参数
      form: {},
      // 审核表单参数
      auditForm: {},
      // 详情表单参数
      detailForm: {},
      // 表单校验
      rules: {
        competitionId: [
          { required: true, message: "竞赛不能为空", trigger: "change" }
        ],
        signupId: [
          { required: true, message: "报名记录不能为空", trigger: "change" }
        ],
        appealTitle: [
          { required: true, message: "申诉标题不能为空", trigger: "blur" },
          { min: 1, max: 30, message: "申诉标题长度在 1 到 30 个字符", trigger: "blur" }
        ],
        appealReason: [
          { required: true, message: "申诉理由不能为空", trigger: "blur" },
          { min: 1, max: 500, message: "申诉理由长度在 1 到 500 个字符", trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" }
        ],
        contactEmail: [
          { required: true, message: "联系邮箱不能为空", trigger: "blur" },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      },
      // 审核表单校验
      auditRules: {
        auditStatus: [
          { required: true, message: "审核状态不能为空", trigger: "change" }
        ],
        auditSuggestion: [
          { required: true, message: "审核建议不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getCompetitionList();
  },
  methods: {
    /** 查询竞赛申诉管理列表 */
    getList() {
      this.loading = true;
      listAppeal(this.queryParams).then(response => {
        console.log('申诉列表响应:', response);
        this.appealList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        console.error('获取申诉列表失败:', error);
        this.loading = false;
      });
    },
    /** 查询竞赛列表 */
    getCompetitionList() {
      console.log('开始获取竞赛列表...');
      // 查询已完赛的竞赛（4已完赛）
      listCompetition({ competitionStatus: 4 }).then(response => {
        console.log('竞赛列表响应:', response);
        this.competitionList = response.rows || [];
      }).catch(error => {
        console.error('获取竞赛列表失败:', error);
        this.competitionList = [];
      });
    },
    /** 查询报名记录列表 */
    getSignupList(competitionId) {
      if (competitionId) {
        console.log('开始获取报名记录列表，竞赛ID:', competitionId);
        listCompetitionSignup({ competitionId: competitionId }).then(response => {
          console.log('报名记录列表响应:', response);
          this.signupList = response.rows || [];
        }).catch(error => {
          console.error('获取报名记录列表失败:', error);
          this.signupList = [];
        });
      } else {
        this.signupList = [];
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消审核按钮
    cancelAudit() {
      this.auditOpen = false;
      this.resetAudit();
    },
    // 取消详情按钮
    cancelDetail() {
      this.detailOpen = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        competitionId: null,
        signupId: null,
        appealTitle: null,
        appealReason: null,
        contactPhone: null,
        contactEmail: null,
        auditStatus: null,
        auditSuggestion: null,
        auditorId: null,
        auditorName: null,
        auditTime: null
      };
      this.signupList = [];
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetFields();
        }
      });
    },
    // 审核表单重置
    resetAudit() {
      this.auditForm = {
        id: null,
        auditStatus: null,
        auditSuggestion: null
      };
      this.$nextTick(() => {
        if (this.$refs.auditForm) {
          this.$refs.auditForm.resetFields();
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$nextTick(() => {
        if (this.$refs.queryForm) {
          this.$refs.queryForm.resetFields();
        }
      });
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加竞赛申诉管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAppeal(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改竞赛申诉管理";
        // 加载对应的报名记录
        if (this.form.competitionId) {
          this.getSignupList(this.form.competitionId);
        }
      });
    },
    /** 审核按钮操作 */
    handleAudit(row) {
      this.resetAudit();
      this.auditForm = {
        id: row.id,
        appealTitle: row.appealTitle,
        appealReason: row.appealReason,
        auditStatus: null,
        auditSuggestion: null
      };
      this.auditOpen = true;
    },
    /** 详情按钮操作 */
    handleDetails(row) {
      this.detailForm = { ...row };
      this.detailOpen = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAppeal(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAppeal(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交审核 */
    submitAudit() {
      this.$refs["auditForm"].validate(valid => {
        if (valid) {
          auditAppeal(this.auditForm).then(response => {
            this.$modal.msgSuccess("审核成功");
            this.auditOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除竞赛申诉管理编号为"' + ids + '"的数据项？').then(function() {
        return delAppeal(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('race/appeal/export', {
        ...this.queryParams
      }, `appeal_${new Date().getTime()}.xlsx`)
    },
    /** 竞赛选择变化 */
    handleCompetitionChange(competitionId) {
      this.form.signupId = null;
      this.getSignupList(competitionId);
    },
    /** 报名记录选择变化 */
    handleSignupChange(signupId) {
      // 可以在这里添加其他逻辑
    },
    /** 格式化时间 */
    parseTime(time, pattern) {
      if (!time) return '';
      const date = new Date(time);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return pattern
        .replace('{y}', year)
        .replace('{m}', month)
        .replace('{d}', day)
        .replace('{h}', hours)
        .replace('{i}', minutes)
        .replace('{s}', seconds);
    }
  }
};
</script>
